package org.demo.system.controller;

import org.demo.base.auth.domain.SysUser;
import org.demo.base.mvc.HttpResult;
import org.demo.base.util.LoginHelper;
import org.demo.system.service.AuthService;
import org.demo.system.service.PermissionService;
import org.demo.system.service.RoleService;
import org.demo.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 认证的相关接口
 * 用户登录、注册、授权之类的
 * @author tomdog
 */
@RestController
public class AuthController {

    @Autowired
    private UserService userService;
    @Autowired
    private AuthService authService;

    /**
     * 注册新用户
     */
    @PostMapping("/register")
    public HttpResult register(@RequestBody SysUser user) {
        // 注册之前的检测
        userService.checkRegister(user);
        // 添加这个用户
        SysUser sysUser = userService.insert(user);
        return HttpResult.success(sysUser);
    }

    /**
     * 登录用户
     */
    @PostMapping("/login")
    public HttpResult login(@RequestBody SysUser user) {
        // 登录检测，成功就返回用户，失败会抛出异常
        SysUser loginUser = authService.login(user);
        // 保存会话信息
        LoginHelper.saveSession(loginUser);
        // 返回登陆成功
        return HttpResult.success(loginUser);
    }

    /**
     * 退出登录
     */
    @GetMapping("/logout")
    public HttpResult logout() {
        // 移除会话
        LoginHelper.invalidSession();
        // 返回登陆成功
        return HttpResult.success();
    }

    /**
     * 获取当前登录的用户
     * @return
     */
    @GetMapping("/currentUser")
    public HttpResult currentLoginUser() {
        SysUser sysUser = LoginHelper.currentLoginUser();
        return HttpResult.success(sysUser);
    }
}
